package com.minjiang.blog.controller.admin;

import com.minjiang.blog.mode.User;
import com.minjiang.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("admin")
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * 登录请求转跳到登录页面
     *
     * @return 返回登录页面
     */
    @GetMapping
    public String loginPage() {
        return "admin/login";
    }
//-------------------------------------------------------

    /**
     * 登录验证
     *
     * @param username
     * @param password
     * @param session
     * @param attributes
     * @return
     */
    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes attributes) {
//       sql语句对比
        User user = userService.checkUser(username, password);
        System.out.println(user);
        if (user != null) {
            session.setAttribute("user", user);
            return "admin/index";
        } else {
            //Model model 重定向拿不到
            attributes.addFlashAttribute("message", "用户和密码错误");
            return "redirect:/admin";
        }

    }

    /**
     * 注销
     */
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/admin";
    }
}
